from flask import Blueprint, request, jsonify, json, make_response
from flask_restful import Resource, Api
from common.utils.captcha.captcha import captcha
from second_flask.methods import db1
from common.utils.myredis import myredis
from common.utils.sdk import send_message
from common.utils.get_data import *
from common.utils.jwt_token import create_token
from flask import current_app as app
from common.utils.get_data import get_data, _get_data
from flask import redirect

# from second_flask.main import send_emial

user_bp = Blueprint('user_bp', __name__)


@user_bp.route('/img_code')
def generate_img_code():
    name, text, img = captcha.generate_captcha()
    response = make_response(img)
    response.headers['Content-Type'] = 'image/jpg'
    uuid = request.args.get('uuid')
    myredis.img_code_set(uuid, 60 * 5, text)
    return response


@user_bp.route('/create_code', methods=['POST'])
def create_code():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    phone = data['phone']
    print('phone>>>>>>', phone)
    sms_code = send_message(phone)
    sms_json = json.dumps(sms_code)
    if sms_json[0] == "000000":
        return {"msg": "连接网络超时", "code": "400"}
    return {"msg": "发送成功", "code": "200"}


@user_bp.route('/check_code', methods=['POST'])
def check_code():
    uuid = get_data()['uuid']
    code = get_data()['code']
    img_code = myredis.str_get(uuid)
    if not img_code:
        return jsonify({'code': 405, 'message': '验证码过期'})
    img_codes = img_code.decode()
    if code.lower() != img_codes.lower():
        return jsonify({'code': 400, 'message': '验证码错误'})
    return jsonify({'code': 200, 'message': '验证码正确'})


@user_bp.route('/phone_login', methods=['POST'])
def phone_login():
    phone = get_data()['phone']
    code = get_data()['code']
    sms_code = myredis.str_get('sms_%s' % (phone))
    if not sms_code:
        return jsonify({'code': 405, "message": '验证码过期'})
    sms_codes = sms_code.decode()
    if sms_codes != code:
        return jsonify({'code': 400, 'message': '验证码错误'})
    sql = "select * from users where phone='%s'" % (phone)
    user = db1.find(sql)
    if not user:
        sql = "insert into users(phone) values('%s')" % (phone)
        db1.update(sql)
        sq = "select * from users where phone='%s'" % (phone)
        users = db1.find(sq)
        user_id = users['id']
        token = create_token(user_id)
        username = users['phone']
        return jsonify({'code': 200, 'token': token, 'username': username, 'user_id': user_id})
    user_id = user['id']
    token = create_token(user_id)
    username = user['phone']
    return jsonify({'code': 200, 'token': token, 'username': username, 'user_id': user_id})


import uuid
from flask_mail import Mail, Message


def send_emails(title, content, emaillist):
    mail = Mail(app)
    m = Message(title, sender='zhy2608347593@163.com', recipients=emaillist)
    m.html = content
    mail.send(m)
    return jsonify({'message': 'ok'})


@user_bp.route('/send_email', methods=['POST'])
def send_email():
    email = get_data()['email']
    print('>>>>>>', email)
    sql = "select id from users where email='%s'" % (email)
    user = db1.find(sql)
    print('user>>>', user)
    if user:
        code = uuid.uuid1().hex
        print('code>>>>', code)
        try:
            send_emails('重置密码', "点击以下<a href='http://localhost:5000/validEmail?code=" + code + "'>链接</a>进行重置", [email])
            myredis.img_code_set(code, 3600, email)
            return jsonify({'code': 200})
        except:
            return jsonify({'code': 400, 'message': '发送邮件失败'})
    else:
        return jsonify({'code': 405, 'message': '该邮箱不存在'})


@user_bp.route('/validEmail')
def valid_Email():
    code = _get_data().get('code')
    print('code>>>>', code)
    email = myredis.str_get(code)
    the_email = email.decode()
    if the_email:
        url = 'http://localhost:8081/update_password?email=' + the_email
        return redirect(url)
    else:
        return jsonify({'code': 403, 'message': '该邮箱不存在'})


from werkzeug.security import generate_password_hash


@user_bp.route('/update_password', methods=['PUT'])
def update_password():
    password = get_data()['password']
    check_password = get_data()['check_password']
    email = get_data()['email']
    if not all([password, check_password]):
        return jsonify({'code': 405, 'message': '不能为空'})
    if password != check_password:
        return jsonify({'code': 400, 'message': '两次输入的密码不一致'})
    secret_password = generate_password_hash(password)
    sql = "update users set password='%s' where email='%s'" % (secret_password, email)
    db1.update(sql)
    return jsonify({'code': 200})



